package com.shutuo.callnumqixintian.utils;



import com.instwall.callbase.tool.LogUtil;
import com.shutuo.callnumqixintian.PostBean;
import com.shutuo.callnumqixintian.QixintianManager;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class ApiUrl {



    public static PostBean getPostUrl(long shop_id, long cashier_id, String appid, String appkey){

        PostBean postBean = new PostBean();

        long time = getUnixTime();

        //The url is encrypted to generate the sig
        String urlEncoded = getSig(getReqEncoded(shop_id,cashier_id),appid,appkey,time);
//        urlEncoded  = "coupons%5B0%5D=12345&coupons%5B1%5D=67890&grade=1&limit=20&offset=0&orderby%5Bbalance%5D=desc&appid=ct_ZjQ4NmU2OTE0OGY1MTJ&appkey=202cb962ac59075b964b07152d234b70&v=2.0&ts=1426773603";
        String sig = md5Decode32(urlEncoded);

        //Request parameters
        String req = getReq(shop_id,cashier_id);
        //Post Url
        postBean.setTime(time);
        postBean.setReq(req);
        postBean.setSig(sig);
        postBean.setAppid(appid);
        return postBean;
    }


    private static String getReq(long shop_id,long cashier_id){
        String req = "{\"shop_id\":"+shop_id+",\"cashier_id\":"+cashier_id+",\"qtId\":null}";
        return req;
    }


    private static String getReqEncoded(long shop_id,long cashier_id){
        String urlEncode = "cashier_id="+cashier_id+"&shop_id="+shop_id;
        return urlEncode;
    }
    private static String getSig(String req ,String appid,String appkey,long time){

        String urlEncode = req+"&appid="+appid+"&appkey="+appkey+"&v=2.0&ts="+time;
        LogUtil.LogI(null, QixintianManager.TAG+"ApiUrl getSig: "+urlEncode);
        return urlEncode;
    }

    private static long getUnixTime(){
        return System.currentTimeMillis()/1000;
    }

    private static String md5Decode32(String content){
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(content.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e){
            throw new RuntimeException("NoSuchAlgorithmException",e);
        } catch (UnsupportedEncodingException e){
            throw new RuntimeException("UnsupportedEncodingException", e);
        }
        //对生成的16字节数组进行补零操作
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash){
            if ((b & 0xFF) < 0x10){
                hex.append("0");
            }
            hex.append(Integer.toHexString(b & 0xFF));
        }
        LogUtil.LogI(null,QixintianManager.TAG+"ApiUrl md5Decode32: "+hex.toString());
        return hex.toString();
    }


}
